package com.longcai.util;


import com.longcai.bean.ApiResult;
import com.longcai.bean.RedisUtil;
import com.longcai.entity.customer.ClyjUser;
import org.springframework.beans.factory.annotation.Autowired;


public class JwtUtil {

    /**
     * 过期时间15分钟
     */
    private static final long EXPIRE_TIME = 15 * 60 * 1000;
    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618";
    @Autowired
    private RedisUtil redisUtil;

   /* public static String sign() {
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            //私钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("try", "JWT");
            header.put("alg", "HS256");
            //附带username。userId信息，生成签名
            return JWT.create().withHeader(header).withClaim("loginName", username)
                    .withClaim("userId", userId)
                    .withExpiresAt(date).sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }

    }*/

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    public ApiResult verify(String token) {
        try {
           /* Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);*/
            boolean b = redisUtil.exists(token);
            ClyjUser clyjUser = (ClyjUser) redisUtil.get(token);
            if (b) {
                return ApiResult.success(clyjUser);
            } else {
                return ApiResult.fail("请先登录");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
